from lib.exts import db
import time

def date2ts(date):
    return int(time.mktime(time.strptime(date, "%Y-%m-%d")))

def ts2date(ts):
    return time.strftime("%Y-%m-%d", time.localtime(ts))

class EntityBase(object):
    def to_json(self):
        fields = self.__dict__.copy()
        if "_sa_instance_state" in fields:
            del fields["_sa_instance_state"]
        
        if "date" in fields:
            fields["date"] = ts2date(fields["date"])    
        
        return fields

class StockLine(db.Model, EntityBase):
    __tablename__ ='stock_line'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    code = db.Column(db.String(10))
    date = db.Column(db.Integer)
    
    open = db.Column(db.Float)
    close = db.Column(db.Float)
    high = db.Column(db.Float)
    low = db.Column(db.Float)
    preclose = db.Column(db.Float)
    
    volume = db.Column(db.Integer)
    def __init__(self, tar_item):
        #self.id = id
        self.code = tar_item['code']
        self.date = date2ts(tar_item['date'])
        self.open = tar_item['open']
        self.close = tar_item['close']
        self.high = tar_item['high']
        self.low = tar_item['low']
        self.preclose = tar_item['preclose']
        self.volume = int(tar_item['volume'])
class ma5_line(db.Model, EntityBase):
    __tablename__ ='ma5_line'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    code = db.Column(db.String(10))
    date = db.Column(db.Integer)
    ma5 = db.Column(db.Float)
    def __init__(self, tar_item):
        #self.id = id
        self.code = tar_item['code']
        self.date = date2ts(tar_item['date'])
        self.ma5 = tar_item['ma5']
